$.ajaxSetup({
	contentType : "application/x-www-form-urlencoded;charset=utf-8",
	cache : false,
	success : function(result, status, xhr) {
	},
	complete: function(xhr, status){
		// 对返回的数据data做判断，
		// session过期的话，就弹出登陆对话框
		var session_status = xhr.getResponseHeader("SESSION_STATUS");
		if(session_status == 'TIMEOUT'){
			$.each(BootstrapDialog.dialogs, function(id, dialog){
                dialog.close();
            });
			BootstrapDialog.show({
				type: BootstrapDialog.TYPE_DEFAULT,
				closable: false,
				draggable: false,
				title: "会话过期，重新登陆!",
				message: $('<div></div>').load(contextPath + "/login/timeout")
			});
		}
	},
	error : function(xhr, status, error) {
		switch (xhr.status) {
		case (500):
			CmMsg.error("服务器系统内部错误", -1);
			break;
		case (400):
			CmMsg.error("请求参数无法识别或转换!", -1);
			break;
		case (401):
			CmMsg.error("未登录", -1);
			break;
		case (403):
			CmMsg.error("您没有权限访问此资源或进行此操作", -1);
			break;
		case (405):
			CmMsg.error("请求的HttpMethod不存在", -1);
			break;
		case (406):
			CmMsg.error("缺失方法，服务器转换参数异常", -1);
			break;
		case (408):
			CmMsg.error("请求超时", -1);
			break;
		default:
			CmMsg.error(error, -1);
		}
	}
});

var ComMsg = function($) {

	this.success = function(message, pos) {
		var position = this.getPos(pos);
		this.send("提示：", message, position, "gritter-success");
	};

	this.error = function(message, pos) {
		var position = this.getPos(pos);
		this.send("错误：", message, position, "gritter-error");
	};

	this.info = function(message, pos) {
		var position = this.getPos(pos);
		this.send("信息：", message, position, "gritter-info");
	};

	this.warn = function(message, pos) {
		var position = this.getPos(pos);
		this.send("警告：", message, position, "gritter-warning");
	};

	this.send = function(title, message, pos, type) {
		// $.gritter.removeAll();
		$.gritter.add({
			title : title,
			text : message,
			time : 1500,
			speed : 500,
			class_name : type + ' gritter-light ' + pos
		});
	};

	this.getPos = function(pos) {
		var position = "";
		switch (pos) {
		case 0:
			position = "gritter-center";
			break;
		default:
			position = "";
		}
		return position;
	}
}
var CmMsg = new ComMsg($);

function getParams(formId) {
	var params = {};
	var formParams = $('#' + formId).serializeArray();
	$.each(formParams, function(name, val) {
		if (val.value !== '') {
			if (params[val.name] !== undefined) {
				if (!params[val.name].push) {
					params[val.name] = [ params[val.name] ];
				}
				params[val.name].push(val.value);
			} else {
				params[val.name] = val.value;
			}
		}
	});
	return params;
}

function initTree(elemId, ajaxUrl, isShowCheck, funs) {
	$("#" + elemId).jstree({
		'core' : {
			"animation" : 200,
			"force_text" : true,
			"check_callback" : true,
			"themes" : {
				"responsive" : true,
				"stripes" : false,
			},
			'data' : {
				'url' : function(node) {
					return ajaxUrl;
				},
				'data' : function(node, elem) {
					if ($.isFunction(funs.query)) {
						return funs.query(node, elem);
					}
					return {
						id : node.id == '#' ? null : node.id
					};
				},
				'type' : 'POST'
			}
		},
		"plugins" : isShowCheck ? [ "checkbox" ] : []
	}).on('loaded.jstree', function(elem, selection) {
		if ($.isFunction(funs.loaded)) {
			funs.loaded(elem, selection);
		}
	}).on('load_node.jstree', function(elem, selection) {
		if ($.isFunction(funs.loadNode)) {
			funs.loadNode(elem, selection);
		}
	}).on('select_node.jstree', function(elem, selection) {
		if ($.isFunction(funs.selNode)) {
			funs.selNode(selection.node, elem);
		}
	});
}

function initTable(tableId, columns, ajaxUrl, searchId) {
	$('#' + tableId).bootstrapTable({
		columns: columns,
		url : ajaxUrl,
		method : 'post',
		contentType : 'application/x-www-form-urlencoded',
		clickToSelect : true,
		sidePagination : 'server',
		queryParamsType : '',
		pageSize : 10,
		paginationFirstText : '首页',
		paginationPreText : '上页',
		paginationNextText : '下页',
		paginationLastText : '末页',
		queryParams : function(params) {
			var finalParams = {};
			if (searchId) {
				var paras = getParams(searchId);
				finalParams = $.extend({}, params, paras);
			} else {
				finalParams = params;
			}
			return finalParams;
		}
	});
	$('#' + tableId).bootstrapTable('resetView');
}

function showAddDlg(title, ajaxUrl, formId, btnCall){
	BootstrapDialog.show({
		type: BootstrapDialog.TYPE_DEFAULT,
		closable:false,
		draggable: true,
		title: title,
		message: $('<div></div>').load(ajaxUrl),
		buttons: [{
		    id: 'btn-OK',   
		    icon: 'glyphicon glyphicon-remove',
		    label: '关闭',
		    cssClass: 'btn-default', 
		    autospin: false,
		    action: function(dialogRef){
		    	dialogRef.close();
		    }
		}, {
			id: 'btn-OK', 
		    icon: 'glyphicon glyphicon-check',
		    label: '确认', 
		    cssClass: 'btn-primary', 
		    autospin: false, 
		    action: function(dialogRef){
		    	if($('#' + formId).valid()){
			    	$.post(ajaxUrl, getParams(formId)).done(function(data){
			    		if(data.status == 'OK'){
			    			dialogRef.close();
			    			CmMsg.success(data.message, -1);
			            	btnCall();
			    		} else if(data.status == 'ERROR'){
			    			CmMsg.error(data.message, -1);
			    		} else if (data.status == 'TIMEOUT'){
			    			CmMsg.error(data.message, -1);
						} else {
			    			CmMsg.error("保存失败或其他错误", -1);
			        	}
			        });
		    	}
		    }
		 }]
	});
}

function showEdtDlg(title, ajaxUrl, tableId, formId, btnCall){
	var selections = $('#' + tableId).bootstrapTable("getSelections");
	if (selections !== undefined && selections !== null) {
		if (selections.length === 1) {
			var id = selections[0].id;
			var formUrl = ajaxUrl + "/" + id;
			BootstrapDialog.show({
					type: BootstrapDialog.TYPE_DEFAULT,
					closable:false,
					draggable: true,
					title: title,
					message: $('<div></div>').load(formUrl),
					buttons: [{
					    id: 'btn-OK',   
					    icon: 'glyphicon glyphicon-remove',
					    label: '关闭',
					    cssClass: 'btn-default', 
					    autospin: false,
					    action: function(dialogRef){
					    	dialogRef.close();
					    }
					}, {
						id: 'btn-OK', 
					    icon: 'glyphicon glyphicon-check',
					    label: '确认', 
					    cssClass: 'btn-primary', 
					    autospin: false, 
					    action: function(dialogRef){
					    	if($('#' + formId).valid()){
						    	$.post(ajaxUrl, getParams(formId)).done(function(data){
						    		if(data.status == 'OK'){
						    			dialogRef.close();
						    			CmMsg.success(data.message, -1);
						            	btnCall();
						    		} else if(data.status == 'ERROR'){
						    			CmMsg.error(data.message, -1);
						    		} else if (data.status == 'TIMEOUT'){
						    			CmMsg.error(data.message, -1);
									} else {
						    			CmMsg.error("编辑失败或其他错误", -1);
						        	}
						        });
						    }
					    }
					}]
				});
		} else {
			CmMsg.warn("请选择一行数据记录进行操作.", -1);
		}
	} else {
		CmMsg.warn("没有选中任何数据记录,无法进行操作.", -1);
	}
}
/**
 * 打开选择list页面
 * @param title
 * @param ajaxUrl
 * @param selectTableIds select页面的tableId数组,如果有多个table需要进行选择
 * @param callBack 回调方法，回传选中的数组obj
 */
function showSelectDlg(title, ajaxUrl, selectTableIds ,callBack){
    BootstrapDialog.show({
        type: BootstrapDialog.TYPE_DEFAULT,
        closable:false,
        draggable: true,
        title: title,
        message: $('<div></div>').load(ajaxUrl),
        buttons: [{
            id: 'btn-OK',   
            icon: 'glyphicon glyphicon-remove',
            label: '关闭',
            cssClass: 'btn-default', 
            autospin: false,
            action: function(dialogRef){
                dialogRef.close();
            }
        }, {
            id: 'btn-OK', 
            icon: 'glyphicon glyphicon-check',
            label: '确认', 
            cssClass: 'btn-primary', 
            autospin: false, 
            action: function(dialogRef){
           		var flag = false;
           		var temp = "";
            	$.each(selectTableIds,function(i,n){
            		var selections = $('#' + n).bootstrapTable("getSelections");
            		if (selections !== undefined && selections !== null) {
            			if (selections.length != 0) {
	            			flag = true;
	            			temp = selections;
            			}
            		}
            	});
            	if(flag){
            		if(callBack){
            			callBack(temp);
            		}
                    dialogRef.close();
                    
            	}else{
            		CmMsg.warn("没有选中任何数据记录,无法进行操作.", -1);
            	}
            }
         }]
    });
}

function doDelete(delUrl, tableId, callback){
	var selections = $('#' + tableId).bootstrapTable("getSelections");
	if (selections !== undefined && selections !== null) {
		if (selections.length == 1) {
			var url = delUrl + "/" + selections[0].id;
			BootstrapDialog.confirm({ 
				title: '确认提示',
				type: BootstrapDialog.TYPE_WARNING,
				btnCancelLabel: '取消', // <-- Default value is 'Cancel',
	            btnOKLabel: '确认', // <-- Default value is 'OK',
				message: "您确定要删除当前选中的数据记录吗?", 
				callback: function(result) {
					if (result) {
				    	$.post(url).done(function(data){
				    		if(data.status == 'OK'){
				    			$('#' + tableId).bootstrapTable('selectPage', 1);
				    			CmMsg.success(data.message, -1);
				    			if(callback){
									callback();
								}
				    		} else if(data.status == 'ERROR'){
				    			CmMsg.error(data.message, -1);
				    		} else if (data.status == 'TIMEOUT'){
				    			CmMsg.error(data.message, -1);
							} else {
				    			CmMsg.error("删除失败了", -1);
				    		}
				    	});
					}
				}
			});
		} else if(selections.length > 1){
			var ids = new Array();
			for (var i = 0; i < selections.length; i++) {
				ids.push(selections[i].id);
			}
			var params = {'ids':ids};
			BootstrapDialog.confirm({ 
				title: '确认提示',
				type: BootstrapDialog.TYPE_WARNING,
				btnCancelLabel: '取消', // <-- Default value is 'Cancel',
	            btnOKLabel: '确认', // <-- Default value is 'OK',
				message:"您确定要删除当前选中的数据记录吗?", 
				callback: function(result) {
				    if (result) {
				    	$.post(delUrl, params).done(function(data){
				    		if(data.status == 'OK'){
				    			$('#' + tableId).bootstrapTable('selectPage', 1);
				    			CmMsg.success(data.message, -1);
				    			if(callback){
									callback();
								}
				    		}else if(data.status == 'ERROR'){
				    			CmMsg.error(data.message, -1);
				    		} else if (data.status == 'TIMEOUT'){
				    			CmMsg.error(data.message, -1);
							} else {
				    			CmMsg.error("删除失败了", -1);
				    		}
				    	});
				    }
				}
			});
		} else {
			CmMsg.warn("请至少选择一行数据记录进行删除.", -1);
		}
	} else {
		CmMsg.warn("没有选中任何数据记录,无法进行删除操作.", -1);
	}
}
/**
 * 选中table数据，访问后台action
 * @param actionUrl
 * @param tableId
 * @param msg 确认框提示信息
 * @param callback
 */
function doAction(actionUrl, tableId, msg, callback){
	var selections = $('#' + tableId).bootstrapTable("getSelections");
	if (selections !== undefined && selections !== null) {
		if (selections.length == 1) {
			var url = actionUrl + "/" + selections[0].id;
			BootstrapDialog.confirm({ 
				title: '确认提示',
				type: BootstrapDialog.TYPE_WARNING,
				btnCancelLabel: '取消', // <-- Default value is 'Cancel',
	            btnOKLabel: '确认', // <-- Default value is 'OK',
				message: msg, 
				callback: function(result) {
					if (result) {
				    	$.post(url).done(function(data){
				    		if(data.status == 'OK'){
				    			$('#' + tableId).bootstrapTable('selectPage', 1);
				    			CmMsg.success(data.message, -1);
				    			if(callback){
									callback();
								}
				    		} else if(data.status == 'ERROR'){
				    			CmMsg.error(data.message, -1);
				    		} else if (data.status == 'TIMEOUT'){
				    			CmMsg.error(data.message, -1);
							} else {
				    			CmMsg.error("操作失败了", -1);
				    		}
				    	});
					}
				}
			});
		} else if(selections.length > 1){
			var ids = new Array();
			for (var i = 0; i < selections.length; i++) {
				ids.push(selections[i].id);
			}
			var params = {'ids':ids};
			BootstrapDialog.confirm({ 
				title: '确认提示',
				type: BootstrapDialog.TYPE_WARNING,
				btnCancelLabel: '取消', // <-- Default value is 'Cancel',
	            btnOKLabel: '确认', // <-- Default value is 'OK',
				message: msg, 
				callback: function(result) {
				    if (result) {
				    	$.post(actionUrl, params).done(function(data){
				    		if(data.status == 'OK'){
				    			$('#' + tableId).bootstrapTable('selectPage', 1);
				    			CmMsg.success(data.message, -1);
				    			if(callback){
									callback();
								}
				    		}else if(data.status == 'ERROR'){
				    			CmMsg.error(data.message, -1);
				    		} else if (data.status == 'TIMEOUT'){
				    			CmMsg.error(data.message, -1);
							} else {
				    			CmMsg.error("操作失败了", -1);
				    		}
				    	});
				    }
				}
			});
		} else {
			CmMsg.warn("请至少选择一行数据记录进行操作.", -1);
		}
	} else {
		CmMsg.warn("没有选中任何数据记录,无法进行操作.", -1);
	}
}
function showComSelRowDlg(title, ajaxUrl, tableId, buttons, size){
	var selections = $('#' + tableId).bootstrapTable("getSelections");
	if (selections !== undefined && selections !== null) {
		if (selections.length === 1) {
			var id = selections[0].id;
			var formUrl = ajaxUrl + "/" + id;
			BootstrapDialog.show({
					type: BootstrapDialog.TYPE_DEFAULT,
					size: size,
					closable:false,
					draggable: true,
					title: title,
					message: $('<div></div>').load(formUrl),
					buttons: buttons
			});
		} else {
			CmMsg.warn("请选择一行数据记录进行操作.", -1);
		}
	} else {
		CmMsg.warn("没有选中任何数据记录,无法进行操作.", -1);
	}
}
/**
 * 初始化文件上传input
 * @param formId
 */
function initFileUpLoad(formId){
	var $form = $("#"+formId);
    var file_input = $form.find("input[type=file]");
    var upload_in_progress = false;
    paramFileUpLoad(file_input);
}
/**
 * 文件上传控件，基本属性配置
 * @param file_input
 */
function paramFileUpLoad(file_input){
	file_input.ace_file_input({
		no_file:'没有文件...',
		btn_choose : "选择或拖拽上传",
		btn_change : "变更文件",
		droppable : true,
		thumbnail : "large",
		maxSize : 2097152,// bytes
		denyExt : [ "exe" ],
		allowExt : [ "jpg","png","jpeg" ],//允许的文件类型
		before_remove : function() {
			if (upload_in_progress){
				return false;// if we are in the middle of uploading a file, don"t allow resetting file input
			}
			return true;
		},
		preview_error : function(filename, code) {
		},
	});
	file_input.on("file.error.ace", function(ev, info) {
		if (info.error_count["ext"] || info.error_count["mime"])
			$.gritter.add({
				title : "系统信息",
				text : "文件格式不正确！只能上传jpg、png、jpeg格式的图片",
				class_name : "gritter-warning gritter-center"
			});
		if (info.error_count["size"])
			$.gritter.add({
				title : "系统信息",
				text : "文件大小不能超过2mb！",
				class_name : "gritter-warning gritter-center"
			});
	});
}

/**
 * 增加上传控件
 * @param divId 
 * @param fileInputName
 */
function addFileUpload(divId,fileInputName){
	var file_input = $("<input type=\"file\" name='"+fileInputName+"' />").appendTo("#" + divId);
	paramFileUpLoad(file_input);
}
/**
 * 保存文件流和表单元素的save方法
 * @param formId 表单formId
 * @param saveOrUpdateUrl 保存或更新url
 * @param dialogRef 模态层对象
 * @param successCallBack 成功回调方法
 */
function saveOrUpdateFileAndForm(formId,saveOrUpdateUrl,dialogRef,successCallBack){
	var $form = $("#"+formId);
	var upload_in_progress = false;
	var file_input = $form.find("input[type=file]");
	var ie_timeout = "";
	
	var _url = saveOrUpdateUrl;
	
	if ("FormData" in window) {//浏览器兼容性
		formData_object = new FormData($("#"+formId)[0]);
		upload_in_progress = true;
		file_input.ace_file_input("loading", false);
		deferred = $.ajax({
			url : _url,
			type : $form.attr("method"),
			processData : false,// important
			contentType : false,// important
			data : formData_object,
			xhr : function() {
				var req = $.ajaxSettings.xhr();
				if (req && req.upload) {
					req.upload.addEventListener("progress", function(e) {
						if (e.lengthComputable) {
							var done = e.loaded || e.position, total = e.total || e.totalSize;
							var percent = parseInt((done / total) * 100) + "%";
						}
					}, false);
				}
				return req;
			},
			beforeSend : function() {
			},
			success : function() {
			}
		});
	} else {
		deferred = new $.Deferred; // create a custom deferred object
		var temporary_iframe_id = "temporary-iframe-" + (new Date()).getTime() + "-" + (parseInt(Math.random() * 1000));
		var temp_iframe = $(
				"<iframe id='" + temporary_iframe_id + "' name='" + temporary_iframe_id +
				"' frameborder='0' width='0' height='0' src='about:blank' style='position:absolute; z-index:-1; visibility: hidden;'></iframe>").insertAfter($form);
		$form.append("<input type='hidden' name='temporary-iframe-id' value='" + temporary_iframe_id + "' />");
		temp_iframe.data("deferrer", deferred);
		$form.attr({
			method : "POST",
			enctype : "multipart/form-data",
			action : _url,
			target : temporary_iframe_id
		});
		upload_in_progress = true;
		file_input.ace_file_input("loading", true);// display an overlay with loading icon

		$form.get(0).submit();
		ie_timeout = setTimeout(function() {
			ie_timeout = null;
			temp_iframe.attr("src", "about:blank").remove();
			deferred.reject({
				"status" : "fail",
				"message" : "Timeout!"
			});
		}, 30000);
	}
	deferred.done(function(result) {// success
		var res = result;//the `result` is formatted by your server side response and is arbitrary
		if (res.status == "OK") {//保存成功
			if(successCallBack){
				successCallBack(res,dialogRef);//调用回调方法
			}
		}
	}).fail(function(result) {// failure
		alert("上传时发生错误");
	}).always(function() {// called on both success and failure
		if (ie_timeout)
			clearTimeout(ie_timeout)
		ie_timeout = null;
		upload_in_progress = false;
		file_input.ace_file_input("loading", false);
	});
	deferred.promise();
}